<?php
/**
 * 用户中心控制器类
 */
namespace Home\Controller;
use Think\Controller;
class UcenterController extends CommonController {
    //用户主页
    public function index(){
        if ($_GET['uid']) {
            $get_uid = I('get.uid');
        } else {
            $get_uid = $_SESSION['uid'];
        }
        $result = UserInfo($get_uid);
        $uqlist = $this->userQuestion($get_uid);
        $ualist = $this->userAnswer($get_uid);
        $this->assign($result);
        $this->assign('body_tag', 'class="fly-full"');
        $this->assign('uqlist', $uqlist);
        $this->assign('ualist', $ualist);
        $this->assign('title', $_SESSION['nickname'].'的主页 - Fly社区');
        $this->display();
    }
    //退出登录方法
    public function logout(){
        session_unset();
        session_destroy();
        setcookie("nickname", '', time()-1, '/');
        echo json_encode(['info'=>'退出帐号成功']);
    }
    //用户中心首页
    public function center(){
        $result = UserInfo($_SESSION['uid']);
        $collection = $this->collection();
        $this->assign($result);
        $this->assign('collection', $collection);
        $this->assign('title', '用户中心 - Fly社区');
        $this->display();
    }
    //帐号设置
    public function setting(){
        $result = UserInfo($_SESSION['uid']);
        $this->assign($result);
        $this->assign('title', '帐号设置 - Fly社区');
        $this->display();
    }
    //消息页面
    public function msg(){
        $this->assign('title', '我的消息 - Fly社区');
        $this->display();
    }
    //产品授权
    public function auz(){
        $this->assign('title', '申请授权 - Fly社区');
        $this->display();
    }
    //修改密码
    public function checkpwd(){
        $data = I('post.');
        $check_old_pwd = M('users')->where('upwd="'.md5($data['nowpass']).'"')->find();
        if ($check_old_pwd) {
            if ($check_old_pwd['upwd'] != md5($data['pass'])) {
                if ($data['pass'] == $data['repass']) {
                    $data['upwd'] = md5($data['pass']);
                    // var_dump($data);exit;
                    $check_old_pwd = M('users')->where('uid='.$_SESSION['uid'])->save($data);

                    if ($check_old_pwd) {
                        $info['info'] = '密码修改成功';
                        echo json_encode($info);
                    } else {
                        $info['error'] = '密码修改失败';
                        echo json_encode($info);
                    }
                } else {
                    $info['error'] = '重复密码不一致';
                    echo json_encode($info);
                }
            } else {
                $info['error'] = '新旧密码不可一致';
                echo json_encode($info);
            }
        } else {
            $info['error'] = '原密码错误';
            echo json_encode($info);
        }
    }
        
    //修改用户信息
    public function checkuinfo(){
        $data = I('post.');
        if ($data['sign'] == '') {
            $data['sign'] = '这个人懒得留下签名';
        }
        if ($data['email'] != $_SESSION['email']) {
            $data['act_email'] = '0';
        }
        $data['uid'] = $_SESSION['uid'];
        $data['uname'] = $data['nickname'];
        $data['uext'] = array(
            'id'=> $_SESSION['uid'],
            'sign'=> $data['sign']);
        unset($data['sign'], $data['nickname']);

        $_SESSION['nickname'] = $data['uname'];
        if ($_SESSION['email'] != $data['email']) {
            $new_email = ['email'=>$data['email'],'act_email'=>'0'];
            M('users')->where('uid='.$_SESSION['uid'])->save($new_email);
            $_SESSION['email'] = $data['email'];
        }
        setcookie("nickname", $data['uname'], time()+31536000, '/');

        $res = D('users')->where('uid='.$_SESSION['uid'])->relation(true)->save($data);

        if($res){
            $info['info'] = '修改成功';
            $info['nickname'] = $_SESSION['nickname'];
            echo json_encode($info);
        }else{
            $info['error'] = '修改失败';
            // echo json_encode($info);
            echo $res;
        }
    }
    //发送邮箱激活邮件
    public function activate(){
        $act_email = M('users')->where('uid="'.$_SESSION['uid'].'"')->field('act_email')->find();
        if ($act_email['act_email'] == 1) {
            echo json_encode(['error'=>'邮箱已激活']);
            exit;
        }
        $token_nums = 3;
        $condition = ['uid'=>$_SESSION['uid']];
        //检查用户激活邮件发送次数
        $send_token = M('users_ext')->where($condition)->field('token_send_times')->find();

        if ($token_nums <= $send_token['token_send_times']) {
            echo json_encode(['error'=>'激活邮件已达一天'.$token_nums.'次发送上限，请明天再试']);
            exit;
        } else {
            // $email = $_SESSION['email'];// 获取用户邮箱
            $email = 'allence_frede@163.com';
            //邮件内容
            $str = <<<act
            <div><includetail><table border="0" cellpadding="0" cellspacing="0" style="width: 600px; border: 1px solid #ddd; border-radius: 3px; color: #555; font-family: 'Helvetica Neue Regular',Helvetica,Arial,Tahoma,'Microsoft YaHei','San Francisco','微软雅黑','Hiragino Sans GB',STHeitiSC-Light; font-size: 12px; height: auto; margin: auto; overflow: hidden; text-align: left; word-break: break-all; word-wrap: break-word;"> <tbody style="margin: 0; padding: 0;"> <tr style="background-color: #393D49; height: 60px; margin: 0; padding: 0;"> <td style="margin: 0; padding: 0;"> <div style="color: #5EB576; margin: 0; margin-left: 30px; padding: 0;"><a style="font-size: 14px; margin: 0; padding: 0; color: #5EB576; text-decoration: none;" href="http://fly.layui.com" target="_blank">Fly社区 - Layui前端框架官方社区</a></div> </td> </tr> <tr style="margin: 0; padding: 0;"> <td style="margin: 0; padding: 30px;"> <p style="line-height: 20px; margin: 0; margin-bottom: 10px; padding: 0;"> Hi，<em style="font-weight: 700;">%s</em>，请完成以下操作： </p> <div style=""> <a href="%s" style="background-color: #009E94; color: #fff; display: inline-block; height: 32px; line-height: 32px; margin: 0 15px 0 0; padding: 0 15px; text-decoration: none;" target="_blank">立即激活邮箱</a> </div> <p style="line-height: 20px; margin-top: 20px; padding: 10px; background-color: #f2f2f2; font-size: 12px;"> 如果该邮件不是由你本人操作，请勿进行激活！否则你的邮箱将会被他人绑定。 </p> </td> </tr> <tr style="background-color: #fafafa; color: #999; height: 35px; margin: 0; padding: 0; text-align: center;"> <td style="margin: 0; padding: 0;">系统邮件，请勿直接回复。</td> </tr> </tbody> </table></includetail></div>
act;

            $act_user = $_SESSION['nickname'];
            //查询激活码
            $token_str = M('users_ext')->where($condition)->field('token')->find();

            $token_str = $token_str['token'];

            $token_url = 'http://'.$_SERVER['HTTP_HOST'].U('home/activate/activate/', array('token'=>$token_str));
            // var_dump($token_url);exit;

            $str = sprintf($str, $act_user, $token_url);

            $title ="librax测试社区激活邮件";

            echo json_encode(actmail($email, $title, $str, $condition, $send_token));
        }
    }

    //更新头像
    public function newavatar()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './avatar/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();

        if(!$info) {// 上传错误提示错误信息
            echo $upload->getError();
        }else{// 上传成功
            $info = current($info);

            $path = "avatar/".$info['savepath'].$info['savename'];

            $_SESSION['avatar'] = $path;

            // $sql ="update user set face='{$path}' where id='{$_SESSION['uid']}'";

            // $res = M()->execute($sql);
            
            $data['uid'] = $_SESSION['uid'];
            $data['uext'] = array(
                'id'=> $_SESSION['uid'],
                'avatar' => $path);

            $res = D('users')->where('uid='.$_SESSION['uid'])->relation(true)->save($data);

            if(!$res){
                echo $path;
            }else{
                echo "0";
            }
        }
    }
    // 管理问题收藏
    public function collection()
    {
        if (!$_POST) {
            $sql = 'select t1.time,t2.title,t2.qid from collection t1 left join question t2 on t1.qid=t2.qid where t1.uid='.$_SESSION['uid'];
            $res = M()->query($sql);
            return $res;
        } else {
            $getpost = I('post.');
            if ($getpost['do'] == 'addCollection') {
                $data = array('uid' => $_SESSION['uid'],
                              'qid' => $getpost['qid'],
                              'time' => time());
                $res = M('collection')->add($data);
                if (!$res) {
                    echo json_encode(['收藏失败']);
                }
            } else if ($getpost['do'] == 'delCollection') {
                $data = array('uid' => $_SESSION['uid'],
                              'qid' => $getpost['qid'],
                              '_logic' => 'and');
                $res = M('collection')->where($data)->delete();
                if (!$res) {
                    echo json_encode(['取消收藏失败']);
                }
            }
        }
        
    }
}